<?php
/**
 * Object Relational Persistence Mapping Class for table: pay_out_receipt
 *
 * @package	com.athena
 * @author	LHV
 */
class PayReceipt extends ORDataObject {

	/**#@+
	 * Fields of table: pay_out_receipt mapped to class members
	 */
	var $pay_receipt_id    = '';
	var $ticket_id		   = '';
	var $patient_id        = '';
	var $patient_code      = '';
	var $created_time      = '';
	var $cashier_id        = '';
	var $cashier_name      = '';
	var $amount            = '';
	var $note              = '';
	var $enum_payment_type = '';
	var $receipt_code          = '';
	var $referenced_receipt    = '';
	/**#@-*/


	/**
	 * DB Table
	 */
	var $_table = 'pay_receipt';

	/**
	 * Primary Key
	 */
	var $_key = 'pay_receipt_id';

	/**
	 * Internal Name
	 */
	var $_internalName = 'PayReceipt';

	/**
	 * Handle instantiation
	 */
	function PayReceipt() {
		parent::ORDataObject();
	}

	public function setData($ticketId, $patientId, $patientCode, $amount, $note,
	   $cashierId, $cashierName, $time, $paymentType, $receiptCode, $repaidReceipt) {
		$data =   array(
		  'ticket_id'         =>  $ticketId,
		  'patient_id'        =>  $patientId,
		  'patient_code'      =>  $patientCode,
		  'amount'            =>  $amount,
		  'note'              =>  $note,
		  'cashier_id'        =>  $cashierId,
		  'cashier_name'      =>  $cashierName,
		  'created_time'      =>  $time,
		  'enum_payment_type' =>  $paymentType,
		  'receipt_code'      =>  $receiptCode,
		  'referenced_receipt'=>  $repaidReceipt
		);
		$this->populateArray($data);
	}

	public function getTicketId() {
		return $this->ticket_id;
	}

	public function getCashierId() {
		return $this->cashier_id;
	}

	public function getAmount() {
		return $this->amount;
	}

	public function getNote() {
		return $this->note;
	}

	public function getTotalAmountByTicket($ticketId) {
        $sql    =   "SELECT SUM(amount) as total_amount FROM $this->_table WHERE ticket_id='$ticketId'";
        $res    =   $this->_execute($sql);
        if ($res && !$res->EOF) {
            return $res->fields['total_amount'];
        }
        return 0;
	}

	public function getPaymentInfoByTicket($ticketId, $paymentType = false) {
		$dateFormat   =   L10nHelper::getSqlDateFormat('YmdHi');
		$sql  =   array(
            'cols'  =>  "pay_receipt_id, receipt_code, referenced_receipt, enum_payment_type,
            			 created_time, DATE_FORMAT(created_time, '$dateFormat') as created_time_formatted,
		                 amount, cashier_id, cashier_name, note",
            'from'      =>  "$this->_table",
            'where'     =>  "ticket_id = '$ticketId' AND amount != 0",
            'orderby'   =>  "enum_payment_type, created_time DESC"
		);
		if ($paymentType !== false) {
			$sql['where']	.=	" AND enum_payment_type='$paymentType'";
		}
		$ds   =   & new Datasource_sql();
		$ds->setup($this->_db, $sql);
		$res  =   $ds->toArray();
		if (count($res) > 0) {
			$paymentTypeList =   Utils::getEnumArrayKey(EnumerationConstant::PAYMENT_COLLECTION_TYPE);
            foreach ($res as &$item) {
                $item['payment_type']       =   $paymentTypeList[$item['enum_payment_type']];
                $item['amount_formatted']	=	L10nHelper::renderNumber($item['amount']);
            }
		}
		return $res;
	}

	public function updateTicketRealPayment($ticketId) {
		$sql  =   "UPDATE pay_payment pp
		          SET pp.real_payment = (SELECT SUM(amount) FROM $this->_table t WHERE t.ticket_id='$ticketId')
		          WHERE pp.ticket_id = '$ticketId'";
        $this->_execute($sql);
	}

	public function getStatisticalPaymentInfo($departmentId, $fromDate = '', $toDate = '',
            $cashierId = false, $onlyInsurancePatient = false) {
        $ds = new Datasource_sql();
        $sql = array(
            'cols'      =>  "sum(pc.amount) real_payment , pc.patient_id, pc.patient_code, pe.name patient_name,
                            pc.cashier_id, pc.cashier_name, pc.note",
            'from'      =>  "pay_receipt pc
	                        INNER JOIN ticket t ON (pc.ticket_id = t.ticket_id)
	                        INNER JOIN person pe ON (t.patient_id = pe.person_id)",
            'where'     => " t.department_id = $departmentId",
            'groupby'   => "pc.ticket_id",
            'orderby'   => "pc.created_time",
        );

        if (!empty($fromDate)) {
            $sql['where'] .= " AND DATE(pc.created_time) >= '$fromDate'";
        }
        if (!empty($toDate)) {
            $sql['where'] .= " AND DATE(pc.created_time) <= '$toDate'";
        }
        if ($cashierId) {
            $sql['where'] .= " AND pc.cashier_id = $cashierId";
        }

        $ds->setup($this->_db, $sql);
        return $ds->toArray();
    }

    public function checkRepaid($receiptCode) {
        $sql    =   "SELECT $this->_key FROM $this->_table WHERE referenced_receipt = '$receiptCode'";
        $res    =   $this->_execute($sql);
        if ($res && !$res->EOF) {
        	return true;
        }
        return false;
    }
    
    /**
     * Generate next receipt code.
     *
     * @return int Receipt code
     */
    public static function genCode() {
        $db     =   Celini::dbInstance();
        $seq    =   $db->genId('pay_receipt_code_sequences');
        return $seq;
    }
    
    /**
     * Get current receipt code.
     *
     * @return int Receipt code
     */
    public static function getCurrentCode() {
        $sql    =   "SELECT id FROM pay_receipt_code_sequences";
        $db     =   Celini::dbInstance();
        $res    =   $db->Execute($sql);
        return $res->fields['id'];
    }
    
    /**
     *  Extended persist funtion. Next receipt code created whenever new receipt created.
     *
     */
    public function persist() {
        if (EnforceType::int($this->get_id()) == 0) {
            $this->genCode();
        }
        parent::persist();
    }
}
?>
